﻿/*
* Do Not Remove
* Author: Douglas Branca http://www.linkedin.com/in/douglasbranca
* CodePlex: https://mvcscriptcompression.codeplex.com 
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace DB.MVC.Extensions.Compression.Cache
{
    /// <summary>
    /// ResourceCache manages the web cache of composite resources
    /// </summary>
    public static class ResourceCache
    {
        /// <summary>
        /// Caches are resource
        /// </summary>
        /// <param name="key">key to cache resource with</param>
        /// <param name="resource">resource string</param>
        /// <param name="context">http context base to use for caching</param>
        public static void CacheResource(string key, string resource, HttpContextBase context)
        {
            if (context.Cache[key] != null)
            {
                context.Cache[key] = resource;
            }
            else
            {
                //add to cache no expiration or dependency
                context.Cache.Insert(key, resource, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(12, 0, 0));
            }
        }

        /// <summary>
        /// Gets a cached resource
        /// </summary>
        /// <param name="key">key to get resource from cache</param>
        /// <param name="context">Http context to use to get cache</param>
        /// <returns>resource string</returns>
        public static string GetCachedResource(string key, HttpContext context)
        {
            if (context.Cache[key] != null)
            {
                return context.Cache[key].ToString();
            }
            else
            {
            
                throw new ArgumentException(string.Format("Cached resource for key {0} not found", key));
            }
        }

        /// <summary>
        /// Checks if the resource key exists in the cache
        /// </summary>
        /// <param name="key">key to check if exists</param>
        /// <param name="context">HttpContextBase to use to check</param>
        /// <returns>true if exists</returns>
        public static bool ExistsInCache(string key, HttpContextBase context)
        {
            return context.Cache[key] != null;
        }
    }
}
